package com.agileai.wm.module.workmanage.handler;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.NullRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;
import com.agileai.wm.common.FileExportHelper;
import com.agileai.wm.module.workmanage.service.WeekWorkAuditManage;

/**
 * generated by miscdp
 */
public class WeekWorkAuditHandler extends SimpleHandler{
	public WeekWorkAuditHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		this.setAttributes(param);
		User user = (User)this.getUser();
		String userId = user.getUserId();
		List<DataRow> groupRecords = getService().getGroupRecords(userId);
		String grpId = param.get("grpId");
		
		String currentUserId = param.get("currentUserId");
		String currentWeekId = param.get("currentWeekId");
		if(groupRecords != null && groupRecords.size() > 0){
			if (StringUtil.isNullOrEmpty(grpId)){
				DataRow row = groupRecords.get(0);
				grpId = row.getString("GRP_ID");
			}

			FormSelect grpFormSelect = new FormSelect();
			grpFormSelect.setKeyColumnName("GRP_ID");
			grpFormSelect.setValueColumnName("GRP_NAME");
			grpFormSelect.putValues(groupRecords);
			grpFormSelect.setSelectedValue(grpId);
			this.setAttribute("grpId", grpFormSelect);
			
			List<DataRow> empRecords = getService().queryEmpRecords(grpId);
			if (empRecords != null && empRecords.size() > 0){
				if (StringUtil.isNullOrEmpty(currentUserId)){
					DataRow userRow = empRecords.get(0);
					currentUserId = userRow.getString("USER_ID");
				}
			}
			
			int markId = 0;
			for(int i=0; i<empRecords.size(); i++){
				DataRow userRow = empRecords.get(i);
				String userIdNum = userRow.getString("USER_ID");
				if(userIdNum.equals(currentUserId)){
					markId = i;
				}
			}
			String currentTabId = param.get("currentTabId");
			if(null == currentTabId || "null".equals(currentTabId)){
				currentTabId = "0";
			}
			if(markId == 0 || "0" == currentTabId || "0".equals(currentTabId)){
				DataRow userRow = empRecords.get(0);
				currentUserId = userRow.getString("USER_ID");
				currentTabId = "0";
			}else{
				currentTabId = String.valueOf(markId);
			}
			
			this.setAttribute("empRecords",empRecords);	
			if (StringUtil.isNullOrEmpty(currentWeekId)){
				DataRow row = getService().retrieveCurrentWeekRow();
				if (row != null && !row.isEmpty()){
					currentWeekId = row.getString("WT_ID");
					this.setAttribute("WT_BEGIN",row.get("WT_BEGIN"));
					this.setAttribute("WT_END",row.get("WT_END"));					
				}
			}else{
				DataRow row = getService().getWeekRow(currentWeekId);
				this.setAttribute("WT_BEGIN",row.get("WT_BEGIN"));
				this.setAttribute("WT_END",row.get("WT_END"));
			}
			if (!StringUtil.isNullOrEmpty(currentWeekId)){
				DataRow weekWorkRow = getService().queryWeekRecord(currentUserId, currentWeekId);
				this.setAttributes(weekWorkRow);
				
				List<DataRow> entryRecords = getService().queryEntryRecords(currentUserId,currentWeekId);
				List<DataRow> prepareRecords = getService().queryPrepareRecords(currentUserId,currentWeekId);
				
				this.setAttribute("entryRecords",entryRecords);	
				this.setAttribute("prepareRecords",prepareRecords);	
//				this.setAttribute("currentTabId", getAttribute("currentTabId",0));
				this.setAttribute("currentTabId", currentTabId);
				this.setAttribute("currentWeekId", currentWeekId);
			}
		}
		
		this.setAttribute("currentUserId", currentUserId);
		
		List<DataRow> userPower=getService().getEmpJobRecords(userId,grpId);
		
		String userEmpJob = null;
		if(!userPower.isEmpty() || userPower.size()>0){
			userEmpJob = userPower.get(0).getString("EMP_JOB");
		}
		if("Master".equals(userEmpJob) ||"Auditer".equals(userEmpJob)){
			setAttribute("exportExcleShow", true);
		}
		if(userPower.size()>0){
			setAttribute("EMP_JOB",userPower.get(0).getString("EMP_JOB"));
		}
		else{
			setAttribute("EMP_JOB","");
		}
		
		setAttribute("ENTRY_STATESelect",FormSelectFactory.create("ENTRY_STATE"));
        setAttribute("WORK_FINISHSelect",FormSelectFactory.create("WORK_FINISH"));
        
        setAttribute("ENTRY_STATE",
                FormSelectFactory.create("ENTRY_STATE")
                    .addSelectedValue(getOperaAttributeValue("ENTRY_STATE","")));
        setAttribute("WW_STATE",
             FormSelectFactory.create("WEEK_WORK_STATE")
                    .addSelectedValue(getOperaAttributeValue("WW_STATE","")));
        setAttribute("WW_COMPLETION",
                FormSelectFactory.create("WORK_FINISH_VALUE")
                    .addSelectedValue(getOperaAttributeValue("WW_COMPLETION","")));
		
		return new LocalRenderer(getPage());
	}
	
	 protected void processPageAttributes(DataParam param) {
		 String userId = getAttributeValue("USER_ID");
	        if (StringUtil.isNullOrEmpty(userId)){
	        	User user =(User)this.getUser();
	        	setAttribute("USER_ID", user.getUserId());
	        }
	        
	        setAttribute("ENTRY_STATESelect",FormSelectFactory.create("ENTRY_STATE"));
	        setAttribute("WORK_FINISHSelect",FormSelectFactory.create("WORK_FINISH"));
	        
	        setAttribute("ENTRY_STATE",
	                FormSelectFactory.create("ENTRY_STATE")
	                    .addSelectedValue(getOperaAttributeValue("ENTRY_STATE","")));
	        setAttribute("WW_STATE",
	             FormSelectFactory.create("WEEK_WORK_STATE")
	                    .addSelectedValue(getOperaAttributeValue("WW_STATE","")));
	        setAttribute("WW_COMPLETION",
	                FormSelectFactory.create("WORK_FINISH_VALUE")
	                    .addSelectedValue(getOperaAttributeValue("WW_COMPLETION","")));
	     }
	
	@PageAction
	public ViewRenderer beforeWeek(DataParam param){
		String currentWeekId = param.get("currentWeekId");
		DataRow row = getService().getBeforeWeekRow(currentWeekId);
		if (row != null && row.size() > 0){
			String wtId = row.getString("WT_ID");
			param.put("currentWeekId",wtId);
		}else{
			this.setErrorMsg("这是第一条周报记录 !!!");
		}
		return prepareDisplay(param);
	}

	@PageAction
	public ViewRenderer nextWeek(DataParam param){
		String currentWeekId = param.get("currentWeekId");
		DataRow row = getService().getNextWeekRow(currentWeekId);
		if (row != null && row.size() > 0){
			String wtId = row.getString("WT_ID");
			param.put("currentWeekId",wtId);
		}else{
			this.setErrorMsg("这是最后一条周报记录!!!");
		}
		return prepareDisplay(param);
	}
	
	@PageAction
	public ViewRenderer currentWeek(DataParam param){
		DataRow row = getService().retrieveCurrentWeekRow();
		String currentWeekId = row.getString("WT_ID");
		param.put("currentWeekId",currentWeekId);
		return prepareDisplay(param);
	}
	
	@PageAction
	public ViewRenderer query(DataParam param){
		return prepareDisplay(param);
	}	
	
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@PageAction
   	public ViewRenderer exportExcleFile(DataParam param) {
    	List<DataRow> userList =getService().getUserList(param);
    	HashMap userMap = new HashMap();
    	for(int i=0;i<userList.size();i++){
    		DataRow userRow = userList.get(i);
    		userMap.put(userRow.getString("USER_ID"), userRow.getString("USER_NAME"));
     	}
    	List<DataRow> weekList =getService().getWeekList(param);
    	List<DataRow> weekPreparreList = getService().getWeekPrepareList(param);
    	HashMap log = new HashMap();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
    	String startTime=param.getString("WT_BEGIN");
    	String endTime=param.getString("WT_END");
    	DataRow getGrpName = getService().getGroupName(param);
    	String fileName="";
		try {
			fileName = getGrpName.getString("GRP_NAME")+"项目周计划"+dateFormat.format(sdf.parse(startTime))+"-"+dateFormat.format(sdf.parse(endTime))+".xls";
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String status="";
    	List<HashMap> logs = new ArrayList<HashMap>();
    	DataRow weekSummarRow = weekList.get(0);
    	List<HashMap> weekSummaryStart = new ArrayList<HashMap>();
    	HashMap logWeek = new HashMap();
    	logWeek.put("content", weekSummarRow.getString("ENTRY_DESCRIBE"));
    	logWeek.put("user", userMap.get(weekSummarRow.get("USER_ID")));
    	
    	String entryReality = weekSummarRow.getString("ENTRY_REALITY");
    	if("null".equals(entryReality) || null == entryReality){
    		logWeek.put("day", "0");
    	}else{
    		logWeek.put("day", weekSummarRow.getString("ENTRY_REALITY"));    		
    	}
    	
    	logWeek.put("date", startTime);
    	
    	String entryFinish = weekSummarRow.getString("ENTRY_FINISH");
    	if("null".equals(entryFinish) || null == entryFinish){
    		status="";
    	}else if(weekSummarRow.getString("ENTRY_FINISH").equals("0")){
    		status="未完成";
    	}else if(weekSummarRow.getString("ENTRY_FINISH").equals("1")){
    		status="完成";
    	}
    	logWeek.put("status", status);
    	logWeek.put("reason", "");
    	weekSummaryStart.add(logWeek);
    	List<HashMap> weekSummary = new ArrayList<HashMap>();
    	for(int i=1;i<weekList.size();i++){
    		logWeek = new HashMap();
    		DataRow weekSummar = weekList.get(i);
    		logWeek.put("content", weekSummar.getString("ENTRY_DESCRIBE"));
        	logWeek.put("user", userMap.get(weekSummar.get("USER_ID")));
        	
        	String entryRealityStr = weekSummar.getString("ENTRY_REALITY");
        	if("null".equals(entryRealityStr) || null == entryRealityStr){
        		logWeek.put("day", "0");
        	}else{
        		logWeek.put("day", weekSummar.getString("ENTRY_REALITY"));    		
        	}
        	
        	logWeek.put("date", startTime);
        	
        	entryFinish = weekSummar.getString("ENTRY_FINISH");
        	if("null".equals(entryFinish) || null == entryFinish){
        		status="";
        	}else if(weekSummar.getString("ENTRY_FINISH").equals("0")){
        		status="未完成";
        	}else if(weekSummar.getString("ENTRY_FINISH").equals("1")){
        		status="已完成";
        	}
        	logWeek.put("status", status);
        	logWeek.put("reason", "");
        	weekSummary.add(logWeek);
    	}
    	
    	String currentWeekId= param.get("currentWeekId");
    	DataRow weekPlanTimeRow =getService().getNextWeekRow(currentWeekId);
    	String nextStartTime = null;
    	if(null == weekPlanTimeRow){
    		nextStartTime = endTime;
    	}else{
    		Date date = (Date) weekPlanTimeRow.get("WT_BEGIN");
    		nextStartTime = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, date);
    	}
    	
    	DataRow weekPlanRow = weekPreparreList.get(0);
    	List<HashMap> weekPlanStart = new ArrayList<HashMap>();
    	HashMap logWeekPlan = new HashMap();
    	logWeekPlan.put("content", weekPlanRow.getString("PRE_DESCRIBE"));
    	logWeekPlan.put("user", userMap.get(weekPlanRow.get("USER_ID")));
    	
    	String preLoad = weekPlanRow.getString("PRE_LOAD");
    	if("null".equals(preLoad) || null == preLoad){
    		logWeekPlan.put("day", "0");
    	}else{
    		logWeekPlan.put("day", weekPlanRow.getString("PRE_LOAD"));    		
    	}
    	
    	logWeekPlan.put("date", nextStartTime);
    	logWeekPlan.put("status", "");
    	logWeekPlan.put("reason", "");
    	weekPlanStart.add(logWeekPlan);
    	
    	List<HashMap> weekPlan = new ArrayList<HashMap>();
    	for(int i=1;i<weekPreparreList.size();i++){
    		logWeek = new HashMap();
    		DataRow dataRow = weekPreparreList.get(i);
    		logWeek.put("content", dataRow.getString("PRE_DESCRIBE"));
        	logWeek.put("user", userMap.get(dataRow.get("USER_ID")));
        	
        	String preLoadStr = dataRow.getString("PRE_LOAD");
        	if("null".equals(preLoadStr) || null == preLoadStr){
        		logWeek.put("day", "0");
        	}else{
        		logWeek.put("day", dataRow.getString("PRE_LOAD"));    		
        	}
        	
        	logWeek.put("date", nextStartTime);
        	logWeek.put("status", "");
        	logWeek.put("reason", "");
        	weekPlan.add(logWeek);
    	}
    	log.put("weekSummaryStart", weekSummaryStart);
    	log.put("weekSummary", weekSummary);
    	log.put("weekPlanStart", weekPlanStart);
    	log.put("weekPlan", weekPlan);
    	log.put("weekSummaryIndex", weekList.size()-1);
    	log.put("weekPlanIndex", weekPreparreList.size()-1);
    	log.put("item", getGrpName.getString("GRP_NAME"));
    	
    	logs.add(log);
    	exportFile(logs, fileName);
       	return new NullRenderer();
   
   	}
    
    @SuppressWarnings({ "unchecked", "rawtypes"})
	private void exportFile(Object model,String fileName) {
		try {
			FileExportHelper fileStreamHelper = new FileExportHelper(request, response);
			String templateDir = fileStreamHelper.getTemplateDirPath();
			String templateFile = "/TeamWeekReport.ftl";
			
			HashMap modelMap = new HashMap();
			modelMap.put("logs", model);
			fileStreamHelper.exportFile(templateDir, templateFile, fileName, modelMap,"utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    protected WeekWorkAuditManage getService() {
        return (WeekWorkAuditManage) this.lookupService(WeekWorkAuditManage.class);
    }

}
